package de.openlaboratory.elib.model.library;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import de.openlaboratory.elib.controller.PublicationDAO;

@Entity
@Table(name = "RENDITIONS")
public class Rendition
{
	@Id
	@GeneratedValue
	private Long id;

	@Column(name = "name")
	private String name;

	@Column(name = "file_type")
	private String type;

	@Column(name = "hash_type", columnDefinition = "varchar(3)")
	private String hashType;

	@Column(name = "hash_value", columnDefinition = "varchar(32)")
	private String hashValue;

	@Column(name = "hash_md5", columnDefinition = "BINDARY(16)")
	private byte md5;

	@ManyToOne
	@JoinColumn(name = "PUBLICATION_ID")
	private Publication publication;

	// position/order for multi-file renditions/chapters/articles
	@Column(name = "order_pos")
	private Integer pos;

	@Transient
	File file;

	public Rendition()
	{
		// TODO Auto-generated constructor stub
	}

	public Rendition(Long id, String name, Integer order, Long publicationId)
	{
		this.id = id;
		this.name = name;
		this.pos = order;
		this.publication = new PublicationDAO().find(publicationId);
	}

	public Long getId()
	{
		return id;
	}

	public void setId(Long id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getType()
	{
		return type;
	}

	public void setType(String type)
	{
		this.type = type;
	}

	public Publication getPublication()
	{
		return publication;
	}

	public void setPublication(Publication publication)
	{
		this.publication = publication;
	}

	public Integer getPos()
	{
		return pos;
	}

	public void setPos(Integer pos)
	{
		this.pos = pos;
	}

	public void setMd5(byte md5)
	{
		this.md5 = md5;
	}

	public void setFile(File file)
	{
		this.file = file;
	}

	private void getMd5()
			throws NoSuchAlgorithmException, IOException
	{
		MessageDigest md = MessageDigest.getInstance("MD5");
		InputStream is = new FileInputStream(this.file.getAbsoluteFile());
		try
		{
			is = new DigestInputStream(is, md);
			// read stream to EOF as normal...
		}
		finally
		{
			is.close();
		}
		byte[] digest = md.digest();
	}
}
